package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string `json:"name"` // 序列化后的key
	Age  int    `json:"age"`
	Addr string `json:"-"` // 忽略字段
}

// 序列化结构体
func testMarshalStruct() {
	p1 := Person{
		Name: "bart",
		Age:  16,
		Addr: "北大街",
	}

	// json, err := json.Marshal(p1)
	json, err := json.Marshal(&p1)
	if err != nil {
		fmt.Println("序列化出错！", err)
	}
	fmt.Println(string(json))
}

// 序列化map
func testMarshalMap() {
	var map01 map[string]interface{}
	map01 = make(map[string]interface{}, 3)
	map01["name"] = "lisa"
	map01["age"] = 13
	map01["addr"] = "west street"

	json, err := json.Marshal(map01)
	// json, err := json.Marshal(&map01)
	if err != nil {
		fmt.Println("序列化出错！", err)
	}
	fmt.Println(string(json))
}

func testUnmarshalStruct() {
	jsoBytes := []byte("{\"addr\":\"west street\",\"age\":13,\"name\":\"lisa\"}")
	var p Person
	err := json.Unmarshal(jsoBytes, &p)
	if err != nil {
		fmt.Println("反序列化出错！", err)
	}
	fmt.Println(p) // {lisa 13 }
}

func testUnmarshalMap() {
	jsoBytes := []byte("{\"addr\":\"west street\",\"age\":13,\"name\":\"lisa\"}")
	var p map[string]interface{} // 反序列化不需要make空间，Unmarshal会帮你做
	err := json.Unmarshal(jsoBytes, &p)
	if err != nil {
		fmt.Println("反序列化出错！", err)
	}
	fmt.Println(p) // map[addr:west street age:13 name:lisa]
}

func main() {
	// testMarshalStruct()
	// testMarshalMap()
	// testUnmarshalStruct()
	testUnmarshalMap()
}
